﻿using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Runtime;

namespace CacheExtensions;

public static class CacheExtensions
{
    public static IServiceCollection AddCache(this IServiceCollection services, IConfigurationSection section)
    {
        var config = section.Get<CacheConfig>() ?? new CacheConfig();

        services.Configure<CacheConfig>(section);

        if (config.Type == CacheType.Memory)
        {
            services.AddDistributedMemoryCache();
            services.AddMemoryCache();

            services.AddSingleton<ICache, MemoryCache>();
        }
        else if (config.Type == CacheType.Redis)
        {
            services.AddStackExchangeRedisCache(options =>
            {
                options.Configuration = config.Redis?.ConnectionString;
                options.InstanceName = config.Prefix;
            });
            services.AddSingleton<ICache, RedisCache>();
        }
        return services;
    }
}
